TMR_WEBCHAT_LAST_ID = undefined;
var texts_el = document.getElementById(TMR_WEBCHAT_TEXTS);
var nick_el = document.getElementById(TMR_WEBCHAT_NICK);
var msg_el = document.getElementById(TMR_WEBCHAT_MSG);
var nick_colors = {
    list: [ 'CornflowerBlue', 'DeepSkyBlue', 
            'Peru', 'Chocolate', 'Firebrick',
            'Orange', 'DarkOrange', 'HotPink', 'PaleVioletRed', 'MediumOrchid'],
    curr_index: 0,
    get_next: function() {
        var result = this.list[this.curr_index];
        this.curr_index += 1;
        if (this.curr_index >= this.list.length) this.curr_index = 0;
        return result;
    },
    color_map: {'Микроша': 'DimGray'},
    get: function (nick) {
        if (!this.color_map[nick]) {this.color_map[nick] = this.get_next()};
        return this.color_map[nick];
    }
};

function urlify(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
};

function update_tmr_webchat() {
    // console.log("updating TMRadio webchat from id " + TMR_WEBCHAT_LAST_ID);
    url = "get?callback=append_webchat_texts";
    if (TMR_WEBCHAT_LAST_ID != undefined) url += "&from_id=" + TMR_WEBCHAT_LAST_ID;
    update_js(url);
};


function append_webchat_texts(data) {
    TMR_WEBCHAT_LAST_ID = data['last_id'];
    var scroll_needed = (data['data'].length > 0) && (texts_el.scrollTop + texts_el.clientHeight == texts_el.scrollHeight);
    beep = false;
    for(var i = 0; i < data['data'].length; i++) {
        beep = true;
        texts_el.appendChild( render_chat_element(data['data'][i]) );
    };
    if (beep) notify_sound();
    if (TMR_WEBCHAT_LIMIT && TMR_WEBCHAT_LIMIT > 0) limit_chat_messages();
    if (scroll_needed) scroll_down();
};

function notify_sound() {
    play_sound('http://files.tmradio.net/.music/c/6/c62b7ce5c791b01be2a44f83750d2b31.mp3');
};

function scroll_down() {
    texts_el.scrollTop = texts_el.scrollHeight;
};

function render_chat_element(msg) {
    var text = urlify(msg.text).replace(/\\n/g,"<br>");
    text = text.replace('\n', '<br>');
    
    if (msg.nick == TMR_WEBCHAT_BOT && FAKE_WEBCHAT_NICKS) {
        var matches = text.match(/^(.*)\((.*)\)(\n)?(<br>)?$/);
        if (matches) {
            msg.nick = matches[2]; text = matches[1];
        } else {
            console.log('brr: ' + text + '|');
        };
    };

    var timestamp = document.createElement('span');
    timestamp.className = 'tmr_timestamp';
    timestamp.innerHTML = msg.time;
    if (msg.nick != undefined) {
        var nick = document.createElement('span');
        nick.className = 'tmr_nick';
        nick.innerHTML = msg.nick + ":";
        nick.onclick = function(){ insert_nick(msg.nick) };
        nick.style.color = nick_colors.get(msg.nick);
    };
    var msg_text = document.createElement('span');
    msg_text.className = 'tmr_msg_text';
    msg_text.innerHTML = text;
    if (msg.nick == 'Микроша' || msg.nick == 'ikitobot') msg_text.style.color = 'DimGray';
    var msg_el = document.createElement('div');
    msg_el.className = 'tmr_chat_message';
    msg_el.appendChild(timestamp);
    msg_el.appendChild(nick);
    msg_el.appendChild(msg_text);
    
    var curr_user_nick = document.getElementById('tmr_webchat_nick').value;
    if (curr_user_nick != '' && text.indexOf(curr_user_nick) != -1) {
        msg_el.style.background = 'MistyRose';
    };

    return msg_el;
};

function send_to_chat() {
    var nick = encodeURI(nick_el.value);
    var message = msg_el.value;
    message = message.replace(/#/g, escape('#')).replace(/\?/g, escape('?'));
    message = message.replace(/&/g, escape('&')).replace(/\+/g, '%2B');
    // var message = encodeURI(msg_el.value);
    url = "send?nick=" + nick + "&text=" + message + "&callback=message_sent";
    update_js(url);
};

function send_to_chat_via_post() {
    real_query = true
    s_el = document.getElementById('simulate_send_to_chat');
    if (s_el != undefined) real_query = !s_el.checked;

    console.log('real_query ' + real_query);
    var nick = nick_el.value;
    var message = msg_el.value;
    message = message.replace(/#/g, escape('#')).replace(/\?/g, escape('?'));
    message = message.replace(/&/g, escape('&')).replace(/\+/g, '%2B');

    params = {}; params.type = 'POST'; params.url = 'http://tmrweb.ikito.ru/chat/send';
    params.data = {nick: nick, text: message};
    if (!real_query) params.data.simulate = 'true';

    params.beforeSend = function() {
        msg_el.value = '';
    };
    params.success = function(data) {
        // console.log('Сообщение отправлено: ' + data);
        window.setTimeout(update_tmr_webchat, 800);
    };
    params.error = function(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.state() != 'rejected') {
            err_text = 'Не удалось отправить сообщение в чат: ' + message;
            texts_el.appendChild( render_chat_element({text: err_text, nick: ''}) );
        } else {
            window.setTimeout(update_tmr_webchat, 800);
        };
    };
    $.ajax(params);
};

function message_sent(result) {
    if (result == 'success') msg_el.value = '';
    if (result == 'error') {
        alert('Не удалось отправить сообщение в чат...');

    };
};

function insert_nick(nick) {
    msg_el.value = nick + ": " + msg_el.value;
};

function limit_chat_messages() {
    while (texts_el.childNodes.length > TMR_WEBCHAT_LIMIT) {
        texts_el.removeChild(texts_el.childNodes[0])
    };
}
// Колбэк, сигнализирующий, что скрипт загрузился и можно вызывать его функции
if (webchat_core_loaded == undefined) { webchat_core_loaded = function() {}; };
webchat_core_loaded();